<template>
    <div class="add-damage">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/affairs/vehicle/damage-list" tag="a">损坏管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
            <li v-if="idEdit">编辑记录</li>
		</nav-header>

        <div class="damage-main" v-loading="loading.status" :element-loading-text="loading.txt">
            <div class="damage-add-head">
                <div class="change-car">
                    <span>车辆信息：</span>
                    <span @click="resetList">选择车辆</span>
                </div>
                <div>
                    <div>
                        <span>厂牌型号：</span>
                        <span>{{carParam.carBrand}}</span>
                    </div>
                    <div>
                        <span>车牌号：</span>
                        <span>{{carParam.carNumber}}</span>
                    </div>
                    <div>
                        <span>车身颜色：</span>
                        <span>{{carParam.color}}</span>
                    </div>
                </div>
            </div>

            <el-form 
                :model="addForm" 
                :rules="rules" 
                ref="addForm" 
                label-width="150px" 
                class="add-form" 
                label-position="left">
                <el-form-item label="损坏时间：" prop="startTime">
                    <el-date-picker
                        v-model="addForm.startTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        value-format="yyyy-MM-dd HH:mm"
                        placeholder="选择时间"
                        @change="getUsePeople"
                        style="width:100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="使用人：">
                    <el-input v-model="addForm.usePeople" maxlength="20" disabled></el-input>
                </el-form-item>
                <el-form-item label="损坏情况：" prop="remark">
                    <el-input
                        type="textarea"
                        placeholder="输入损坏情况"
                        :rows="4"
                        v-model="addForm.remark"
                        maxlength="100"
                        show-word-limit>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="车辆照片：" class="car-picture">
                    <uploader 
                        :options="uploadOptions" 
                        :autoStart="true" 
                        ref="uploader" 
                        :file-status-text="statusText"
                        @files-submitted="fileSubmit"
                        @file-removed="fileRemoved" 
                        @file-success="fileSuccess" 
                        @file-error="fileFail"  
                        class="uploader-example">
                            <uploader-unsupport></uploader-unsupport>
                            <uploader-btn :directory="false" :attrs="attrs" :single="true" v-show="selectFileShow">
                                <i class="el-icon-plus avatar-uploader-icon"></i>
                            </uploader-btn>
                            <div class="car-picture-show">
                                <div  class="cover-box" v-show="!selectFileShow">
                                    <img :src="BASE_URL + previewImgURL" />

                                    <div class="uploader-close-box">
                                        <label class="el-upload-list__item-status-label" @click.stop="imgRemove">
                                            <transition name="el-fade-in-linear">
                                                <i class="el-icon-upload-success el-icon-check"></i>
                                            </transition>
                                            <transition name="el-fade-in-linear">
                                                <i class="el-icon-close"></i>
                                            </transition>
                                        </label>
                                    </div>
                                </div>
                            </div>
                    </uploader>
                </el-form-item>
                <el-form-item label="是否报废：">
                    <el-switch v-model="addForm.scrapped"></el-switch>
                    <span class="scrapped-tips">提示：选择报废后，车辆不可再使用</span>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="resetForm" plain>取消</el-button>
                    <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-dialog 
            title="选择车辆" 
            :visible.sync="carVisible" 
            class="cars-manage" 
            width="800px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <div>
                <div class="cars-content-head">
                    <div class="search-text">
                        <el-select v-model="newParam.typeId" filterable placeholder="请选择车型">
                            <el-option
                                v-for="item in typeList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
						<el-input v-model="newParam.keyword" placeholder="搜索车牌号、厂家型号" @keyup.enter.native="searchFunc"></el-input>
                        <div>
                            <el-button type="primary" @click="searchFunc">搜索</el-button>
                            <el-button type="primary" @click="resetList">重置</el-button>
                        </div>
                    </div>
                </div>

                <div class="zh-table-contents">
                    <el-table
                        :data="listData"
                        fixed
                        border
                        ref="multipleTable"
                        highlight-current-row
						@row-click="showCarsRadio"
                        style="width: 100%">
                        <el-table-column
							type="index"
							label="序号"
							width="50">
							<template slot-scope="scope">
								<el-radio class="radio" v-model="selCars" :label="scope.$index">&nbsp;</el-radio>
							</template>
						</el-table-column>
                        <el-table-column
                            prop="brand"
                            label="厂家型号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="number"
                            label="车牌号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="type_name"
                            label="车型"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="color"
                            label="颜色"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                    </el-table>

                    <div class="table-pagination" v-show="newParam.totalNumber > 10">
                        <el-pagination
                            @size-change="setCurrentSize"
                            @current-change="setCurrentPage"
                            :current-page="newParam.pageIndex"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="newParam.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="newParam.totalNumber">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitNewCar('recordForm')">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {uploaderFileFail} from './../../../tools/tool';

export default {
    data() {
        return {
            idEdit: false,
            carVisible: false, // 显示车辆列表
            selectFileShow: true,//是否显示选择文件按钮
            selCars: '', // 选中车辆
            selCarsId: '', // 选中车辆 id
            previewImgURL: '', // 图片预览
            listData: [],
            typeList: [{id: 0, name: '全部车型'}], // 车型列表
            imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
            loading: {
                status: false,
                txt: '保存数据...'
            },
            newParam: {
                typeId: 0, // 车型
                keyword: '', // 关键字
                pageSize: 10,
                pageIndex: 1,
                totalNumber: 0
            },
            carParam: {
                id: null,
                carBrand: '-',
                carNumber: '-',
                color: '-'
            },
            addForm: {
                startTime: '', // 损坏时间
                usePeople: '', // 使用人
                useId: null,
                remark: '', // 损坏情况
                scrapped: false, // 是否报废
                picture: {
                    file_path: ''
                }
            },
            rules: {
                startTime: [
                    { required: true, message: '请选择损坏时间', trigger: 'change' }
                ],
                remark: [
                    { required: true, message: '请输入损坏情况', trigger: 'blur' }
                ],
            },
             attrs: {
                accept: ['image/*']
            },
            statusText: {
                success: '上传成功',  
                error: '上传出错',  
                uploading: '正在上传...',  
                paused: '暂停',  
                waiting: '等待上传'  
            },
            uploadOptions: {
                target: this.BASE_URL + '/api/resource/res_upload',
                testChunks: false,
                headers: {Authorization: `Bearer ` + this.$g.access_token},
            },
        }
    },
    created() {
        this.idEdit = this.$route.params.id ? true : false;
        this.getModeList();

        if (this.idEdit) {
            this.getInfo();
        }
    },
    methods: {
        /**
         * 获取编辑信息
         */
        getInfo() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;

                if (!is_empty(res.data)) {
                    let picture = [];
                    res.data.image.forEach(item => {
                        picture.push({
                            file_path: item
                        })
                    })
                    this.addForm = {
                        startTime: res.data.damage_day,
                        usePeople: res.data.user_name,
                        useId: res.data.user_id,
                        scrapped: res.data.is_useless,
                        picture: picture,
                        remark: res.data.comment,
                    }

                    this.selCarsId = res.data.car_id;
                    if (res.data.image.length > 0) {
                        this.selectFileShow = false;
                        this.previewImgURL = res.data.image[0];
                    }
                    this.carParam =  {
                        id: res.data.car_id,
                        carBrand: res.data.car_brand,
                        carNumber: res.data.car_number,
                        color: res.data.car_color
                    }
                }
            })
            const params = {
                id: this.$route.params.id
            }

            this.$ajax.get('api/car/damagesingle', {params, func:{success: success}})
        },
        /**
         * 获取车辆类型列表
         */
        getModeList() {
            const success = (res=>{
                this.typeList = res.data;
                this.typeList.unshift({
                    id: 0, 
                    name: '全部车型'
                })
            })
            const params = {
                in_use: 0 // 是否已有汽车类型（1：是，0：否（默认））
            }

            this.$ajax.get('api/car/typelists', {params, func: {success: success}})
        },
        /**
         * 获取用车人
         */
        getUsePeople(val) {
            let success = (res => {
                if (res.data.id != 0) {
                    this.addForm.useId = res.data.id;
                    this.addForm.usePeople = res.data.name;
                } else {
                    this.$message.warning('该时间无用车人');
                    this.addForm.useId = null;
                    this.addForm.usePeople = '-';
                }
            })
            let params = {
                car_id: this.selCarsId,
                return_day: this.addForm.startTime
            }

            this.$ajax.get('api/car/caruser', {params: params, func:{success: success}});
        },
        /**
         * 获取车辆列表
         */
        getList() {
            let success = (res => {
                this.carVisible = true;
                this.listData = res.data.data;
                this.newParam.totalNumber = res.data.data_sum;
            })
            let params = {
                page_index: this.newParam.pageIndex,
                page_size: this.newParam.pageSize,
                type_id: this.newParam.typeId,
                keyword: this.newParam.keyword,
                with_image: 0
            }

            this.$ajax.get('api/car/lists',{params, func:{success: success}})
        },
        /**
         * 搜索列表
         */
        searchFunc() {
            this.newParam.pageIndex = 1;
            this.getList();
        },
        /**
         * 重置车辆列表
         */
        resetList() {
            this.newParam = {
                typeId: 0,
                keyword: '',
                pageSize: 10,
                pageIndex: 1
            }

            this.getList();
        },
        /**
         * 单选框，选择点击的数据
         * @param {Object} row 当前行数据
         */
        showCarsRadio(row) {
            this.selCars = this.listData.indexOf(row);
            this.selCarsId = row.id;
        },
        /**
         * 保存车辆信息
         */
        submitNewCar() {
            this.carVisible = false;

            this.carParam = {
                id: this.listData[this.selCars].id,
                carBrand: this.listData[this.selCars].brand,
                carNumber: this.listData[this.selCars].number,
                color: this.listData[this.selCars].color
            }
        },
        /**
         * 保存添加车辆
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.idEdit) {
                        let yes = (res => {
                            this.saveInfo();
                        })
                        let cancel = (res => {
                            this.$router.push('/affairs/vehicle/damage-list');
                        })

                        this.e_confirm({yes: yes, cancel: cancel, txt: '是否要保存损坏信息修改?'});
                    } else {
                        this.saveInfo();
                    }
                } else {
                    return false;
                }
            });
        },
        saveInfo() {
            this.loading.status = true;

            let params = {
                car_id: this.selCarsId,
                user_id: this.addForm.useId,
                damage_day: this.addForm.startTime,
                is_useless: this.addForm.scrapped ? 1 : 0,
                comment: this.addForm.remark,
                path: [this.addForm.picture.file_path]
            }

            const success = (res => {
                this.$message.success(res.msg);
                
                this.$router.push('/affairs/vehicle/damage-list');
            })
            const fail = (res => {
                this.$message.error(res.msg);
                this.loading.status = false;
            })
            
            if (this.idEdit) {
                params.id = this.$route.params.id;
                this.$ajax.put("api/car/damagesingle", params, {func: {success: success, fail: fail}});
            } else {
                this.$ajax.post("api/car/damagesingle", params, {func: {success: success, fail: fail}});
            }
        },
        /**
         * 取消添加记录
         */
        resetForm() {
            this.$router.go(-1);
        },
        /**
         * 关闭弹窗
         */
        cancelForm() {
            this.carVisible = false;
        },
        /**
         * 设置每页列表的数量
         * @param {Number} val 每页数据条数
         */
        setCurrentSize(val) {
            this.newParam.pageIndex = 1;
            this.newParam.pageSize = val;

            this.getList();
        },
        /**
         * 设置当前列表的页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.newParam.pageIndex = val;

            this.getList();
        },
        /**
         * 移除图片
         */
        imgRemove() {
            this.selectFileShow = true;
            this.previewImgURL = '';
            this.addForm.picture.file_path = undefined;
            this.$refs.uploader.uploader.cancel();
        },
        /**
         * 过滤文件格式
         */
        fileSubmit(files, fileList, event){
            for (let i=0; i<fileList.length; i++) {
                let file_type = fileList[i].fileType.toLocaleLowerCase();

                if(!this.imageType.includes(file_type)){
                    this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
                    this.$refs.uploader.uploader.removeFile(fileList[i]);

                    return false;
                } else if (fileList[i].size > 10240000) {
                    this.$message.warning("只允许上传10M以内的文件");
                    this.$refs.uploader.uploader.removeFile(fileList[i]);
                    return false;
                } else {
                    if(this.$refs.uploader.uploader.fileList.length > 1){
                        //删除第一张图片
                        this.$refs.uploader.uploader.removeFile(this.$refs.uploader.uploader.fileList[0]);
                    }

                    this.previewImgURL = window.URL.createObjectURL(fileList[i].file);
                }
            }
        },
        /**
         * 上传成功回调
         */
        fileSuccess (rootFile, file, message, chunk) { 
            let mess = eval('(' + message + ')');
            mess = handleResponseData( mess );

            if(parseInt(mess.data.status) === 1 ){
                this.selectFileShow = false;
                this.addForm.picture.file_name = mess.data.file_name;
                this.addForm.picture.file_path = mess.data.file_path;
                this.addForm.picture.post_fix = mess.data.post_fix;
                this.previewImgURL = mess.data.file_path;
            }
        },
        /**
         * 上传失败回调
         */
        fileFail(rootFile, file, message, chunk) {
            uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
        },
        /**
         * 移除文件
         */
        fileRemoved(file){
            this.selectFileShow = true;
            this.previewImgURL = '';
        },
    },
}
</script>

<style lang="scss">
.add-damage {
    .scrapped-tips {
        margin-left: 25px;
        color: #f56c6c;
    }

    .damage-main {
        .damage-add-head {
            margin-bottom: 35px;
            padding-bottom: 30px;
            width: 650px;
            border-bottom: 1px dotted #ddd;

            .change-car {
                margin-bottom: 28px;
                    
                >span:first-child {
                    display: inline-block;
                    width: 100px;
                }   
                
                >span:last-child {
                    color: #348EFC;
                    cursor: pointer;
                }
            }

            .change-car + div {
                display: flex;
                justify-content: space-between;

                div span:first-child {
                    display: inline-block;
                    width: 100px;
                }
            }
        }

        form {
            .el-form-item__content {
                width: 500px;
            }
        }

        .car-picture {
            .uploader-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 190px;
                height: 190px;
                background: #FFFFFF;
                border: 1px dashed #ddd;
                box-sizing: border-box;

                i  {
                    font-size: 60px;
                    color: #ddd;
                }
            }

            .cover-box {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 190px;
                height: 190px;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .uploader-close-box {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    z-index: 99;
                    overflow: hidden;

                    .el-upload-list__item-status-label {
                        display: block;
                        position: absolute;
                        right: -17px;
                        top: -7px;
                        width: 46px;
                        height: 26px;
                        background: #13ce66;
                        text-align: center;
                        transform: rotate(45deg);
                        box-shadow: 0 1px 1px #ccc;
                        .el-icon-check {
                            position: absolute;
                            left: 17px;
                            font-size: 12px;
                            margin-top: 12px;
                            color: #fff;
                            transform: rotate(-45deg);
                            font-family: 'element-icons' !important;
                            speak: none;
                            font-style: normal;
                            font-weight: normal;
                            font-variant: normal;
                            text-transform: none;
                            line-height: 1;
                            vertical-align: baseline;
                            display: inline-block;
                            -webkit-font-smoothing: antialiased;
                        }
                        .el-icon-check:before {
                            content: "\E6DA";
                        }
                        .el-icon-close {
                            display: none;
                        }
                    }
                }
                .uploader-close-box:hover {
                    background: rgba(0, 0, 0, .3);
                    .el-upload-list__item-status-label {
                        top: -4px;
                        right: -15px;
                        background: #f56c6c;
                        box-shadow: none;
                        cursor: pointer;
                        .el-icon-check {
                            display: none;
                        }
                        .el-icon-close {
                            position: absolute;
                            transform: rotate(-45deg);
                            top: 10px;
                            color: #fff;
                            right: 16px;
                            font-size: 12px;
                            font-family: 'element-icons' !important;
                            speak: none;
                            font-style: normal;
                            font-weight: normal;
                            font-variant: normal;
                            text-transform: none;
                            line-height: 1;
                            vertical-align: baseline;
                            display: inline-block;
                            -webkit-font-smoothing: antialiased;
                        }
                        .el-icon-close:before {
                            content: "\E6DB";
                        }
                    }
                }
            }
        }
    }

    .cars-manage {
        .el-dialog__body {
            padding-bottom: 40px;
        }
    }

    .cars-content-head {
        .search-text {
            display: flex;
            margin: 20px 0;

            >div:first-child {
                width: 160px;
            }

            >div:nth-child(2) {
                margin: 0 20px;
                width: 160px;
            }
        }
    }
}
</style>